package com.platform.modules.quality.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.util.StringUtil;
import com.platform.common.utils.DownloadUtils;
import com.platform.common.utils.Query;
import com.platform.common.utils.StringUtils;
import com.platform.dto.MessageSendDto;
import com.platform.modules.prj.entity.PrjWorkAreaEntity;
import com.platform.modules.prj.service.PrjWorkAreaService;
import com.platform.modules.quality.dao.QlyInspectionDao;
import com.platform.modules.quality.entity.QlyInspectionEntity;
import com.platform.modules.quality.service.QlyInspectionService;
import com.platform.modules.quality.vo.QlyInspectionStatusQuantityByAppVo;
import com.platform.service.MessageHandleService;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class QlyInspectionServiceImpl extends ServiceImpl<QlyInspectionDao, QlyInspectionEntity> implements QlyInspectionService {

    private static final Logger logger = LoggerFactory.getLogger(QlyInspectionServiceImpl.class);
    
    @Autowired
    PrjWorkAreaService prjWorkAreaService;

    @Autowired
    MessageHandleService messageHandleService;
	
//	@Override
//    public boolean save(QlyInspectionEntity qlyInspectionEntity) {
//		return this.saveOrUpdate(qlyInspectionEntity);
//	}
	
	@Override
    public List<QlyInspectionEntity> queryList(Map<String, Object> params) {
        return baseMapper.selectList(params);//baseMapper.selectAll(params);
    }

    @Override
    public Page<QlyInspectionEntity> queryPage(Map<String, Object> params) {    	
        params.put("sidx", "T.CREATE_TIME");
        params.put("asc", false);
        Page<QlyInspectionEntity> page = new Query<QlyInspectionEntity>(params).getPage();
        List<QlyInspectionEntity> list = baseMapper.selectList(page, params);
        return page.setRecords(list);
    }

	@Override
	public void updateQueNum(String insId, Integer value) {
		QlyInspectionEntity entity = baseMapper.selectById(insId);
		entity.setQueNum(entity.getQueNum() + value);
		baseMapper.updateById(entity);
	}

	@Override
	public Page<QlyInspectionEntity> queryPageByApp(Map<String, Object> params) {
		params.put("sidx", "T.CREATE_TIME");
        params.put("asc", false);
        Page<QlyInspectionEntity> page = new Query<QlyInspectionEntity>(params).getPage();
        List<QlyInspectionEntity> list = baseMapper.selectListByApp(page, params);
        return page.setRecords(list);
	}

	@Override
	public void overdue(String overDate) {
		//默认时间为当天
		if(StringUtil.isEmpty(overDate)) {
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
			overDate = df.format(new Date());// new Date()为获取当前系统时间
		}
		overDate = overDate + " 00:00:00";
		
		//更新所有超期未整改记录
		Integer overdueNumber = baseMapper.overdue(overDate);		
		logger.info("overDate:"+overDate+" baseMapper.overdue() 超期数量:"+overdueNumber);		
		
	}

	@Override
	public QlyInspectionStatusQuantityByAppVo statusQuantity(String prjId) {
		QlyInspectionStatusQuantityByAppVo statusQuantity = new QlyInspectionStatusQuantityByAppVo();
		statusQuantity.setPrjId(prjId);
		statusQuantity.setReformedQuantity(0L);
		statusQuantity.setReviewQuantity(0L);
		statusQuantity.setCompletedQuantity(0L);
		statusQuantity.setAllQuantity(0L);
		List<Map<String,Object>> list = baseMapper.statusQuantity(prjId);
		for(Map<String,Object> m : list) {
			String queStatus = (String)m.get("queStatus");
			Long quantity = (Long)m.get("quantity");
			//问题状态：1待整改 4超期未整改 合并
			if("1".equals(queStatus) || "4".equals(queStatus)) {
				statusQuantity.setReformedQuantity(statusQuantity.getReformedQuantity()+quantity);
			}else if("2".equals(queStatus)){
				statusQuantity.setReviewQuantity(statusQuantity.getReviewQuantity()+quantity);
			}else if("3".equals(queStatus)){
				statusQuantity.setCompletedQuantity(statusQuantity.getCompletedQuantity()+quantity);
			}
			statusQuantity.setAllQuantity(statusQuantity.getAllQuantity()+quantity);
		}
		return statusQuantity;
	}

	@Override
	@Async
	public void sendMessage(QlyInspectionEntity qlyInspectionEntity) {
		String workAreaParentId = qlyInspectionEntity.getWorkAreaParentId();
		if(StringUtil.isEmpty(workAreaParentId)) {
			logger.error("发送质量巡查推送消息异常, 巡查记录ID:{}, 原因:工区不能为空",qlyInspectionEntity.getInsId());
			return ;
		}
		PrjWorkAreaEntity prjWorkAreaEntity = prjWorkAreaService.getById(workAreaParentId);
		if(null==prjWorkAreaEntity) {
			logger.error("发送质量巡查推送消息异常, 工区ID:{}, 原因:未找到工区",workAreaParentId);
			return ;
		}
		if(null==prjWorkAreaEntity.getResponsibleUserId()) {
			logger.error("发送质量巡查推送消息异常, 工区ID:{}, 原因:未找到工区组负责人",workAreaParentId);
			return ;
		}
		
    	MessageSendDto messageSendDto = new MessageSendDto();
    	messageSendDto.setClientId("smartcs");
    	messageSendDto.setSaveFlag(true);
    	messageSendDto.setTemplateCode("ZLXC_GQFZR");
    	messageSendDto.setUserId(prjWorkAreaEntity.getResponsibleUserId());
    	messageSendDto.setUserThirdId(prjWorkAreaEntity.getResponsibleUserId());
    	Map<String, String> extend = new HashMap<String, String>();
    	extend.put("ag1", qlyInspectionEntity.getInsId());
    	
    	messageSendDto.setExtend(extend);
    	
    	messageHandleService.send(messageSendDto);
		
	}

	@Override
	@Async
	public void sendMessage(String userId, String templateCode, String insId) {
		MessageSendDto messageSendDto = new MessageSendDto();
    	messageSendDto.setClientId("smartcs");
    	messageSendDto.setSaveFlag(true);
    	messageSendDto.setTemplateCode(templateCode);
    	messageSendDto.setUserId(userId);
    	messageSendDto.setUserThirdId(userId);
    	Map<String, String> extend = new HashMap<String, String>();
    	extend.put("ag1", insId);    	
    	messageSendDto.setExtend(extend);
    	
    	messageHandleService.send(messageSendDto);
	}
}
